// yangbuyi Copyright (c) https://yby6.com 2023.

package com.yby6.tencentaigc.controller;


import com.tencentcloudapi.tts.v20190823.models.TextToVoiceRequest;
import com.yby6.tencentaigc.resp.R;
import com.yby6.tencentaigc.utils.TencentUtils;
import com.yby6.tencentaigc.utils.XunFeiUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

/**
 * 语音合成
 *
 * @author Yang Shuai
 * Create By 2023/12/21
 */
@RequestMapping("/speechSynthesis")
@RestController
@RequiredArgsConstructor
public class AudioController {


    private static final Logger log = LoggerFactory.getLogger(AudioController.class);


    @PostMapping("tencentTextToVoice")
    public R<String> tencentTextToVoice(@RequestBody TextToVoiceRequest request) {
        return R.ok(TencentUtils.textToVoice(request));
    }



    /**
     * 获取讯飞音频流
     *
     * @return {@link byte[]}
     */
    private static byte[] getAudioByte(String text) {
        text = text.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "").trim();
        //调用微服务接口获取音频base64
        String result = "";
        try {
            result = XunFeiUtil.convertText(text);
        } catch (Exception e) {
            log.error("【文字转语音接口调用异常】", e);
        }
        // 音频数据
        return Base64.getDecoder().decode(result);
    }


    /**
     * 生成语音返回流
     */
    @PostMapping(value = "textToAudio")
    public void textToAudio(@RequestParam String text, HttpServletResponse response) throws IOException {
        if (StringUtils.isNotBlank(text)) {
            //过滤图片,h5标签
            final byte[] audioByte = getAudioByte(text);
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            try {
                //音频流
                os.write(audioByte);
            } catch (IOException e) {
                log.error("音频数据异常", e);
            } finally {
                os.flush();
                os.close();
            }
        }
    }


}

